package mspbots.autotask.data.core.tasks;


import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Log4j2
@Component
@RequiredArgsConstructor
public class TasksReceiver {

    private final TasksRepository tasksRepository;

    @RabbitListener(queues = "auto-task.tasks.sync")
    public void syncTask(ResultMsg content) {

        Tasks tasks = Tasks.builder().otherId(content.getId())
                .tenantId(content.getTenantId()).syncTime(content.getSyncDate())
                .createdTime(LocalDateTime.parse(content.getEntity().get("createDateTime").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .updatedTime(LocalDateTime.parse(content.getEntity().get("lastActivityDateTime").textValue(),
                        DateTimeFormatter.ISO_OFFSET_DATE_TIME))
                .entity(content.getEntity())
                .build();

        this.tasksRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(oldTask -> {
                    tasks.setId(oldTask.getId());
                    return tasks;
                })
                .defaultIfEmpty(tasks)
                .flatMap(this.tasksRepository::save).block(Duration.ofSeconds(10));

    }
}
